// Vue 应用配置
const { createApp } = Vue;

// 初始化应用
const app = createApp({
    data() {
        return {
            notes: [],
            showNewNote: false,
            showSearch: false,
            editingNote: null,
            searchQuery: '',
            selectedTag: '',
            tagInput: '',
            currentNote: {
                title: '',
                content: '',
                tags: []
            }
        };
    },
    
    computed: {
        filteredNotes() {
            let filtered = this.notes;
            
            // 搜索过滤
            if (this.searchQuery) {
                const query = this.searchQuery.toLowerCase();
                filtered = filtered.filter(note =>
                    note.title.toLowerCase().includes(query) ||
                    note.content.toLowerCase().includes(query) ||
                    note.tags.some(tag => tag.toLowerCase().includes(query))
                );
            }
            
            // 标签过滤
            if (this.selectedTag) {
                filtered = filtered.filter(note => note.tags.includes(this.selectedTag));
            }
            
            return filtered;
        },
        
        allTags() {
            const tags = new Set();
            this.notes.forEach(note => {
                note.tags.forEach(tag => tags.add(tag));
            });
            return Array.from(tags).sort();
        }
    },
    
    async mounted() {
        await this.loadNotes();
        
        // 配置 marked
        marked.setOptions({
            highlight: function(code, lang) {
                if (Prism.languages[lang]) {
                    return Prism.highlight(code, Prism.languages[lang], lang);
                }
                return code;
            },
            breaks: true,
            gfm: true
        });
    },
    
    methods: {
        async loadNotes() {
            try {
                this.notes = await storage.getAllNotes();
            } catch (error) {
                console.error('加载笔记失败:', error);
                alert('加载笔记失败，请刷新页面重试');
            }
        },
        
        formatDate(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diff = now - date;
            
            // 小于1分钟
            if (diff < 60000) {
                return '刚刚';
            }
            
            // 小于1小时
            if (diff < 3600000) {
                return `${Math.floor(diff / 60000)} 分钟前`;
            }
            
            // 小于1天
            if (diff < 86400000) {
                return `${Math.floor(diff / 3600000)} 小时前`;
            }
            
            // 小于7天
            if (diff < 604800000) {
                return `${Math.floor(diff / 86400000)} 天前`;
            }
            
            // 其他情况显示完整日期
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        },
        
        renderMarkdown(text) {
            if (!text) return '';
            return marked.parse(text);
        },
        
        addTag() {
            const tags = this.tagInput.split(',').map(tag => tag.trim()).filter(tag => tag);
            tags.forEach(tag => {
                if (!this.currentNote.tags.includes(tag)) {
                    this.currentNote.tags.push(tag);
                }
            });
            this.tagInput = '';
        },
        
        removeTag(tag) {
            const index = this.currentNote.tags.indexOf(tag);
            if (index > -1) {
                this.currentNote.tags.splice(index, 1);
            }
        },
        
        insertCode() {
            const codeBlock = '\n```javascript\n// 在这里输入代码\n```\n';
            this.insertAtCursor(codeBlock);
        },
        
        insertBold() {
            this.insertAtCursor('**加粗文本**');
        },
        
        insertItalic() {
            this.insertAtCursor('*斜体文本*');
        },
        
        insertAtCursor(text) {
            const textarea = document.querySelector('textarea');
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const currentText = textarea.value;
            
            const newText = currentText.substring(0, start) + text + currentText.substring(end);
            this.currentNote.content = newText;
            
            // 设置光标位置
            this.$nextTick(() => {
                textarea.focus();
                textarea.setSelectionRange(start + text.length, start + text.length);
            });
        },
        
        async saveNote() {
            if (!this.currentNote.title.trim()) {
                alert('请输入标题');
                return;
            }
            
            try {
                if (this.editingNote) {
                    // 更新现有笔记
                    const updatedNote = {
                        ...this.editingNote,
                        ...this.currentNote
                    };
                    await storage.updateNote(updatedNote);
                } else {
                    // 创建新笔记
                    await storage.addNote(this.currentNote);
                }
                
                await this.loadNotes();
                this.cancelEdit();
            } catch (error) {
                console.error('保存笔记失败:', error);
                alert('保存失败，请重试');
            }
        },
        
        editNote(note) {
            this.editingNote = note;
            this.currentNote = {
                title: note.title,
                content: note.content,
                tags: [...note.tags]
            };
        },
        
        cancelEdit() {
            this.showNewNote = false;
            this.editingNote = null;
            this.currentNote = {
                title: '',
                content: '',
                tags: []
            };
            this.tagInput = '';
        },
        
        async exportData() {
            try {
                const data = await storage.exportData();
                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `学习笔记备份_${new Date().toISOString().split('T')[0]}.json`;
                a.click();
                URL.revokeObjectURL(url);
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败，请重试');
            }
        },
        
        importData() {
            document.getElementById('fileInput').click();
        },
        
        async handleFileImport(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            try {
                const text = await file.text();
                const data = JSON.parse(text);
                
                if (confirm(`确定要导入 ${data.notes?.length || 0} 篇笔记吗？这将覆盖现有数据。`)) {
                    await storage.importData(data);
                    await this.loadNotes();
                    alert('导入成功！');
                }
            } catch (error) {
                console.error('导入失败:', error);
                alert('导入失败，请检查文件格式');
            }
            
            // 清空文件输入
            event.target.value = '';
        }
    }
});

// 挂载应用
app.mount('#app');